
/**
 * Copyright 2007 Jason Horman, Pete Aykroyd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.functor;

import org.codehaus.janino.ExpressionEvaluator;

import java.lang.reflect.InvocationTargetException;

/**
 * A {@link UnaryProcedure} that can dynamically execute an expression using
 * janino.
 */
public class DynamicUnaryProcedure<P> extends UnaryProcedure<P> {
	private ExpressionEvaluator ee;

	/**
	 * Construct a new dynamic function. The parameter name in the expression will
	 * be "x".
	 */
	public DynamicUnaryProcedure(String expression, Class parameterType) {
		try {
			ee = new ExpressionEvaluator(expression, Void.TYPE, new String[]{"x"}, new Class[]{parameterType});
		} catch (Exception e) {
			throw new ExpressionException("Couldn't compile expression", e);
		}
	}

	/**
	 * Evaluates the expression.
	 * @throws RuntimeException If the expression throws an exception.
	 */
	public void run(P o) {
		try {
			ee.evaluate(new Object[] { o });
		} catch (InvocationTargetException e) {
			throw new ExpressionException("Error evaluating expression", e);
		}
	}
}
